package com.sjft.cloud.commons.datasource.config;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.sjft.cloud.commons.datasource.aspect.DataSourceAspect;
import com.sjft.cloud.commons.datasource.constant.DataSourceType;
import com.sjft.cloud.commons.datasource.dynamic.DynamicDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置
 *
 * @author Jin
 */
@Configuration(proxyBeanMethods = false)
@Import(DataSourceAspect.class)
@AutoConfigureBefore(value = {MybatisPlusAutoConfiguration.class})
@ConditionalOnProperty(name = {"spring.datasource.read_write.enable"}, havingValue = "true")
public class DynamicDataSourceConfig {


    @RefreshScope
    @Bean(name = "writeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.write")
    public DataSource firstDataSource() {
        return new HikariDataSource();
    }

    @RefreshScope
    @Bean(name = "readDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.read")
    public DataSource secondDataSource() {
        return new HikariDataSource();
    }

    @RefreshScope
    @Primary
    @Bean(name = "dataSource")
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.WRITE.name(), firstDataSource);
        targetDataSources.put(DataSourceType.READ.name(), secondDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }

    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
